
//
//  YYYHomePictureView.swift
//  HotNews
//
//  Created by YYY on 2017/10/25.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit

class YYYHomePictureView: UIView {

    //设置配图的高度
    var viewModel: YYYHomeViewModel?
    {
        didSet
        {
            //设置配图视图大小
            calculateViewSize()
            //设置配图的URL
            urls = viewModel?.picUrls
        }
    }
    //设置配图视图大小
    private func calculateViewSize()
    {
        //设置配图视图高度
        setHeight(newHeight: viewModel?.pictureSize.height ?? 0)
        //根据配图视图个数，设置第一张图像大小
        let count = viewModel?.picUrls?.count ?? 0
        
        if count == 1
        {
            //单张图像 根据缓存的图像大小进行显示
            let singleImage = subviews[0]
            let singleWidth = viewModel?.pictureSize.width ?? 0
            let singleHeight = viewModel?.pictureSize.height ?? 0
            singleImage.frame = CGRect(x: 0, y: kPictureViewOutterMargin, width: singleWidth, height: singleHeight - kPictureViewOutterMargin)
            let subImageView = singleImage.subviews[0]
            subImageView.setLeft(newLeft: singleImage.width - subImageView.width)
            subImageView.setTop(newTop: singleImage.height - subImageView.height)
        }
        else if count > 1
        {
            //多张图像 恢复九宫格的布局
            let singleImage = subviews[0]
            singleImage.frame = CGRect(x: 0, y: kPictureViewOutterMargin, width: kPictureItemWidth, height: kPictureItemWidth)
            
            singleImage.subviews[0].setRight(newRight: singleImage.width-singleImage.subviews[0].width)
            singleImage.subviews[0].setTop(newTop: singleImage.height - singleImage.subviews[0].height)
            let subImageView = singleImage.subviews[0]
            subImageView.setLeft(newLeft: singleImage.width - subImageView.width)
            subImageView.setTop(newTop: singleImage.height - subImageView.height)
        }
    }
    //设置配图的URL
    private var urls: [YYYPictureModel]?
    {
        didSet
        {
            for view in subviews
            {
                //隐藏所有子视图
                view.isHidden = true
            }
            var index = 0
            //根据索引进行遍历
            for url in urls ?? []
            {
                let subImageView = subviews[index] as! UIImageView
                //取消隐藏
                subImageView.isHidden = false
                //处理4张图片
                if index==1 && urls?.count == 4
                {
                    index += 1
                }
                subImageView.sd_setImageUrl(urlString: url.thumbnail_pic, placeholderString: nil)
                index += 1
                
                var tempString = url.thumbnail_pic ?? ""
                tempString = (tempString as NSString).pathExtension.lowercased()
                subImageView.subviews[0].isHidden = (tempString != "gif")
                
            }
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
      
        //可裁剪的
        clipsToBounds = true
        //初始化界面
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    /// @param selectedIndex    选中照片索引
    /// @param urls             浏览照片 URL 字符串数组
    /// @param parentImageViews 父视图的图像视图数组，用户展现和解除转场动画参照
    @objc private func tapGesture(gesture: UITapGestureRecognizer)
    {
        guard let img = gesture.view,
              let picUrls = viewModel?.picUrls else
        {
            return
        }
        //选中的图片索引
        var selectedIndex = img.tag
        //thumbnail_pic
        //largePic
        let urls = (picUrls as NSArray).value(forKey: "largePic") as! [String]
        if selectedIndex > 1 && urls.count == 4
        {
            selectedIndex += 1
        }
        var imageViewList = [UIImageView]()
        
        for img in (subviews as! [UIImageView])
        {
            if !img.isHidden
            {
                imageViewList.append(img)
            }
        }
        //发送通知
        let userInfo: [String: Any] = [PhotoBrowserUrlsKey: urls,
                        PhotoBrowserSelectedIndexKey: selectedIndex,
                        PhotoBrowserParentImageViewsKey: imageViewList
                        ]
        NotificationCenter.default.post(name: NSNotification.Name(rawValue: PhotoBrowserNotification), object: self, userInfo: userInfo)
    }
}
extension YYYHomePictureView
{
    //初始化界面
    private func setupUI()
    {
        //设置背景颜色
        backgroundColor = superview?.backgroundColor
        
        let count = 3
        let rect = CGRect(x: 0, y: kPictureViewOutterMargin, width: kPictureItemWidth, height: kPictureItemWidth)
        
        for i in 0 ..< count * count
        {
            let itemImageView = UIImageView()
            //0 1 2
            let row = CGFloat(i / count) //0
            let col = CGFloat(i % count) //1
            let xOffset = col * (kPictureItemWidth + kPictureViewInnerMargin)
            let yOffset = row * (kPictureItemWidth + kPictureViewInnerMargin)
            itemImageView.frame = rect.offsetBy(dx: xOffset, dy: yOffset)
            addSubview(itemImageView)
            //可裁剪的
            itemImageView.clipsToBounds = true
            //设置显示模式
            itemImageView.contentMode = .scaleAspectFill
            
            //打开交互
            itemImageView.isUserInteractionEnabled = true
            //添加手势识别方法
            let gesture = UITapGestureRecognizer(target: self, action: #selector(tapGesture))
            itemImageView.addGestureRecognizer(gesture)
            //设置tag值
            itemImageView.tag = i
            
            //添加GIF图片
            addGifImage(itemImageView)
        }
    }
    
    //添加GIF图片
    private func addGifImage(_ itemImageView: UIImageView)
    {
        let gifImage = UIImageView(image: UIImage(named: "timeline_image_gif"))
        itemImageView.addSubview(gifImage)
        gifImage.setLeft(newLeft: itemImageView.width - gifImage.width)
        gifImage.setTop(newTop: itemImageView.height - gifImage.height)
    }
}
